package com.iddaa.core.service.impl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection;

import net.spy.memcached.MemcachedClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.iddaa.core.annotation.Memcached;
import com.iddaa.core.annotation.MemcachedRead;
import com.iddaa.core.dao.CountryDAO;
import com.iddaa.core.domain.Country;
import com.iddaa.core.service.CountryService;
import com.iddaa.core.util.Constants;

@Service("countryService")
@Memcached(prefix = "Country", expiration = Constants.Cache.COUNTRY_EXPIRETIME)
public class CountryServiceImpl implements CountryService {

	@Autowired
	private CountryDAO countryDAO;

	@Override
	public void deleteCountry(Long id) {
		countryDAO.delete(findById(id));
		deleteCache(id);
	}

	@Override
	@MemcachedRead
	public Country findById(Long id) {
		return countryDAO.getById(id);
	}

	@Override
	public Collection<Country> loadAll() {
		return countryDAO.loadAll();
	}

	@Override
	public void saveCountry(Country country) {
		countryDAO.saveOrUpdate(country);
		evictCache(country);
	}

	@Async
	public void evictCache(Country country) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.set("Country:" + country.getId(), Constants.Cache.COUNTRY_EXPIRETIME, country);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Async
	public void deleteCache(Long id) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.delete("Country:" + id);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
